package com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.zhjd.common.util.ZhjdIotUtils;
import com.ruoyi.zhjd.laboratory.modules.errorRecord.service.ErrorRecordService;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.entity.MarshallStabilityNewEntity;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.entity.MarshallStabilityNewProcessResEntity;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.entity.MarshallStabilityNewResEntity;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.mapper.MarshallStabilityNewMapper;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.service.MarshallStabilityNewProcessResService;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.service.MarshallStabilityNewResService;
import com.ruoyi.zhjd.laboratory.modules.marshallStabilityNew.service.MarshallStabilityNewService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("marshallStabilityNewService")
public class MarshallStabilityNewServiceImpl extends ServiceImpl<MarshallStabilityNewMapper, MarshallStabilityNewEntity> implements MarshallStabilityNewService {

    @Autowired
    private MarshallStabilityNewMapper marshallStabilityNewMapper;

//    @Autowired
//    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private MarshallStabilityNewResService marshallStabilityNewResService;

    @Autowired
    private MarshallStabilityNewProcessResService marshallStabilityNewProcessResService;

    @Autowired
    private ErrorRecordService errorRecordService;

    private static Map<String,String> currentMap = new HashMap<>();

    /**
     * 列表
     */
    @Override
    public IPage<JSONObject> queryPage(Map<String, Object> params) {
//        IPage<MarshallStabilityNewEntity> page = baseServiceComponent.getPage(params, MarshallStabilityNewEntity.class);
        return marshallStabilityNewMapper.queryPage(null,params);
    }

    /**
     * 信息
     * @return MarshallStabilityNewEntity
     */
    @Override
    public MarshallStabilityNewEntity getInfo(String id){
        return getById(id);
    }

    /**
     * 保存
     */
    @Override
    public void saveData(MarshallStabilityNewEntity marshallStabilityNew){
        save(marshallStabilityNew);
    }

    /**
     * 修改
     */
    @Override
    public void updateData(MarshallStabilityNewEntity marshallStabilityNew){
        updateById(marshallStabilityNew);
    }

    /**
     * 删除单条数据
     * @param id
     */
    @Override
    public void deleteOneData(String id){
        removeById(id);
    }

    /**
     * 删除
     */
    @Override
    public void deleteData(List<String> ids){
        removeByIds(ids);
    }

    /**
     *  解析马歇尔稳定度测定仪数据
     * @param resData 试验结果数据
     * @param deviceId 试验设备id
     */
    @Override
    public void parsingData(String resData,String deviceId){
        Date nowDate = new Date();
        try {
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(resData);
            //如果数据以00开头，可能设备刚开机或重启，表示一次新的实验开始
            if(StringUtils.equals(dataList.get(0),"00")){
                currentMap.remove(deviceId);
            }
            //验证位不进行校验
            int i = 4;
            //试验数据
            if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_TEST, dataList.get(i))) {
                MarshallStabilityNewEntity entity = new MarshallStabilityNewEntity();
                entity.setDeviceId(deviceId);
                if(currentMap.get(deviceId) == null){
                    MarshallStabilityNewResEntity resEntity = new MarshallStabilityNewResEntity();
                    resEntity.setDeviceId(deviceId);
                    marshallStabilityNewResService.save(resEntity);
                    currentMap.put(deviceId,resEntity.getId());
                }
                //设置实验结果数据id
                entity.setResId(currentMap.get(deviceId));

                entity.setOriginalData(resData);
                entity.setCreateTime(nowDate);
                i++;
                entity.setFlag(dataList.get(i));

                // 将16进制转换为10进制数据，不含（0x）
                // 稳定度值WD，2字节无符号数，高位在前，2位小数。如2356，表示23.56KN
                i++;
                String wd = "" + Integer.parseInt(dataList.get(i),16) + Integer.parseInt(dataList.get(i + 1),16);
                entity.setWd(ZhjdIotUtils.subByDecimalPlaces(2,wd));

                //流值FLUX，2字节无符号数，高位在前，2位小数。如367，表示3.67MM
                i += 2;
                String flux = "" + Integer.parseInt(dataList.get(i),16) + Integer.parseInt(dataList.get(i + 1),16);
                entity.setFlux(ZhjdIotUtils.subByDecimalPlaces(2,flux));

                save(entity);
                //结果数据
            } else if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_RES, dataList.get(i))) {
                MarshallStabilityNewResEntity resEntity = new MarshallStabilityNewResEntity();
                resEntity.setId(currentMap.get(deviceId));
                currentMap.remove(deviceId);
                resEntity.setDeviceId(deviceId);
                resEntity.setOriginalData(resData);
                resEntity.setCreateTime(nowDate);

                // 将16进制转换为10进制数据，不含（0x）
                // 稳定度值WD，2字节无符号数，高位在前，2位小数。如2356，表示23.56KN
                i++;
                String wd = "" + Integer.parseInt(dataList.get(i),16) + "." + Integer.parseInt(dataList.get(i + 1),16);
//                resEntity.setWd(ZhjdIotUtils.subByDecimalPlaces(2,wd));
                resEntity.setWd(new BigDecimal(wd));

//
                //流值FLUX，2字节无符号数，高位在前，2位小数。如367，表示3.67MM
                i += 2;
                String flux = "" + Integer.parseInt(dataList.get(i),16) + "." + Integer.parseInt(dataList.get(i + 1),16);
//                resEntity.setFlux(ZhjdIotUtils.subByDecimalPlaces(2,flux));
                resEntity.setFlux(new BigDecimal(flux));
                marshallStabilityNewResService.saveOrUpdate(resEntity);
                //结果过程数据
            } else if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_PROCESS, dataList.get(i))) {
                MarshallStabilityNewProcessResEntity processEntity = new MarshallStabilityNewProcessResEntity();
                processEntity.setDeviceId(currentMap.get(deviceId));
                processEntity.setDeviceId(deviceId);
                processEntity.setOriginalData(resData);
                processEntity.setCreateTime(nowDate);
                marshallStabilityNewProcessResService.save(processEntity);
            }  else {
                throw new ServiceException("马歇尔稳定度数据解析异常：" + resData);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.MARSHALL_STABILITY_NEW,deviceId,resData);
            throw new ServiceException("数据解析异常");
        }
    }

    /**
     * 批处理历史数据,重新进行解析过程数据
     */
    public void reparseData(){
        //获取所有数据
        List<MarshallStabilityNewEntity> list = marshallStabilityNewMapper.selectList(new QueryWrapper<>());
        for(MarshallStabilityNewEntity item : list){
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(item.getOriginalData());
            int i = 4;
            //试验数据
            MarshallStabilityNewEntity entity = item;
            i++;
            entity.setFlag(dataList.get(i));

            // 将16进制转换为10进制数据，不含（0x）
            // 稳定度值WD，2字节无符号数，高位在前，2位小数。如2356，表示23.56KN
            i++;
            String wd = "" + Integer.parseInt(dataList.get(i),16) + "." +Integer.parseInt(dataList.get(i + 1),16);
//            entity.setWd(ZhjdIotUtils.subByDecimalPlaces(2,wd));
            entity.setWd(new BigDecimal(wd));
            //流值FLUX，2字节无符号数，高位在前，2位小数。如367，表示3.67MM
            i += 2;
            String flux = "" + Integer.parseInt(dataList.get(i),16) + "." + Integer.parseInt(dataList.get(i + 1),16);
//            entity.setFlux(ZhjdIotUtils.subByDecimalPlaces(2,flux));
            entity.setFlux(new BigDecimal(flux));
            updateById(entity);
        }
    }

    /**
     * 绑定材料
     * @param marshallStabilityNewRes
     */
    public void changeSample(MarshallStabilityNewResEntity marshallStabilityNewRes){
        //更新试验结果表
        marshallStabilityNewResService.updateById(marshallStabilityNewRes);
        //查询试验过程数据
        List<MarshallStabilityNewEntity> processList = list(new LambdaQueryWrapper<MarshallStabilityNewEntity>().eq(MarshallStabilityNewEntity::getResId,marshallStabilityNewRes.getId()));
        if(CollectionUtil.isNotEmpty(processList)){
            for(MarshallStabilityNewEntity item : processList){
                item.setSampleId(marshallStabilityNewRes.getSampleId());
            }
            updateBatchById(processList);
        }
    }
}
